package com.spbl.web;

import com.spbl.common.ConstantUtil;
import com.spbl.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * Description(登录出管理)
 * author: Gao xueyong
 * Create at: 2020/6/7 10:30 上午
 */
@Slf4j
@Controller
public class LoginManageController {
    @Autowired
    private SysUserService sysUserService;
    @RequestMapping("/login.html")
    public String loginTemplate() {
        return "login";
    }

    @PostMapping("/login")
    public String login(HttpServletRequest request, Model model) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            String name = "World";
            model.addAttribute("name", name);
            model.addAttribute("subject", subject);
            request.getSession().setAttribute("user",sysUserService.getSysUserByLoginName(username));
            return "redirect:/index";
        } catch (Exception e) {
            log.error("登录失败", e);
        }
        return "error";
    }
}